package com.mentalhealthplatform.schoolV1.service;

import com.mentalhealthplatform.appModels.Teacher;
import com.mentalhealthplatform.exception.others.ResourceNotFoundException;
import com.mentalhealthplatform.exception.user.UserAlreadyExistsException;
import com.mentalhealthplatform.global.rbac.model.User;
import com.mentalhealthplatform.global.rbac.service.entity.BaseUserService;
import com.mentalhealthplatform.schoolV1.dto.TeacherDTO;
import com.mentalhealthplatform.schoolV1.repository.TeacherRepositoryV1;
import com.mentalhealthplatform.utils.PagedResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class TeacherServiceV1 {

    private static final Logger logger = LoggerFactory.getLogger(TeacherServiceV1.class);

    @Autowired
    private BaseUserService baseUserService;

    @Autowired
    private TeacherRepositoryV1 teacherRepositoryV1;

    @Autowired
    private PasswordEncoder passwordEncoder;

    // 获取所有教师信息（分页、过滤、排序）
    public PagedResponse<TeacherDTO> getTeachers(String name, String department, String college, String gender,
                                                 LocalDateTime startDate, LocalDateTime endDate,
                                                 Pageable pageable) {

        // 使用 TeacherRepository 进行分页查询
        Page<Teacher> teachersPage = teacherRepositoryV1.findByFilters(name, department, college, gender, startDate, endDate, pageable);

        // 将 Teacher 实体转换为 TeacherDTO
        List<TeacherDTO> teacherDTOs = teachersPage.getContent().stream()
                .map(TeacherDTO::convertToDTO)
                .collect(Collectors.toList());

        // 创建并返回分页响应
        return new PagedResponse<>(teacherDTOs, teachersPage.getNumber(), teachersPage.getSize(),
                teachersPage.getTotalElements(), teachersPage.getTotalPages(), teachersPage.isLast());
    }

    // 根据教师ID获取教师信息
    public TeacherDTO getTeacherById(UUID teacherId) {
        Teacher teacher = teacherRepositoryV1.findById(teacherId)
                .orElseThrow(() -> new ResourceNotFoundException("Teacher not found with id " + teacherId));
        return TeacherDTO.convertToDTO(teacher);
    }

    // 根据工号获取教师信息
    public TeacherDTO getTeacherByNumber(String number) {
        Teacher teacher = teacherRepositoryV1.findByNumber(number)
                .orElseThrow(() -> new ResourceNotFoundException("Teacher not found with number " + number));
        return TeacherDTO.convertToDTO(teacher);
    }

    public TeacherDTO addTeacher(TeacherDTO teacherDTO) {
        // 通过 username 查找是否已有该用户
        Optional<User> userOptional = baseUserService.findByUsername(teacherDTO.getNumber());

        // 如果用户不存在，创建新用户
        if (userOptional.isEmpty()) {

            teacherDTO.setUsername(teacherDTO.getNumber());

            // 将 TeacherDTO 转换为 Teacher 实体
            Teacher teacher = teacherDTO.convertToEntity();

            teacher.setPassword(passwordEncoder.encode("123456"));

            // 保存 Teacher 实体（JPA 会处理继承关系）
            Teacher savedTeacher = teacherRepositoryV1.save(teacher);

            // 返回保存后的 TeacherDTO
            return TeacherDTO.convertToDTO(savedTeacher);
        } else {
            // 如果用户已经存在，抛出自定义异常
            throw new UserAlreadyExistsException("用户名已存在: " + teacherDTO.getName());
        }
    }


    // 更新教师信息
    public TeacherDTO updateTeacher(UUID teacherId, TeacherDTO teacherDTO) {
        Teacher teacher = teacherRepositoryV1.findById(teacherId)
                .orElseThrow(() -> new ResourceNotFoundException("Teacher not found with id " + teacherId));

        teacher.setUsername(teacherDTO.getUsername());
        teacher.setPhone(teacherDTO.getPhone());
        teacher.setStatus(teacherDTO.isStatus());
        teacher.setDepartment(teacherDTO.getDepartment());
        teacher.setCollege(teacherDTO.getCollege());
        teacher.setAddress(teacherDTO.getAddress());
        teacher.setBirthDate(teacherDTO.getBirthDate());
        teacher.setName(teacherDTO.getName());
        teacher.setNumber(teacherDTO.getNumber());
        teacher.setGender(teacherDTO.getGender());

        Teacher updatedTeacher = teacherRepositoryV1.save(teacher);
        return TeacherDTO.convertToDTO(updatedTeacher);
    }

    // 删除教师
    public void deleteTeacher(UUID teacherId) {
        teacherRepositoryV1.deleteById(teacherId);
    }

    // 批量删除教师
    public void batchDeleteTeachers(List<UUID> ids) {
        teacherRepositoryV1.deleteAllByIdIn(ids);
    }
}
